﻿CREATE PROCEDURE [dbo].[CreateProcess]
	@DownloadQueueID BIGINT,
	@ProcessType NVARCHAR(250),
	@Result NVARCHAR(250)
AS
BEGIN
	BEGIN TRY
		SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
		SET NOCOUNT ON;
		DECLARE @tmp TABLE (pk BIGINT);
		DECLARE @id BIGINT;
		DECLARE @datacounter INT;
		DECLARE @report XML;

		INSERT INTO [Queue].[vwProcess] (DownloadQueueID, ProcessType, Result, CreatedBy, DateCreated, DateDeleted, VersionDate, VersionUser)
		OUTPUT Inserted.ProcessQueueID INTO @tmp
		VALUES (@DownloadQueueID, @ProcessType, @Result, SYSTEM_USER, GETDATE(), NULL, GETDATE(), SYSTEM_USER);
		SELECT @id = pk FROM @tmp
		
		SELECT @datacounter = @@ROWCOUNT;
		SET @report = (SELECT	'Row added to Process Queue'	AS LogMessage,
								GETDATE()						AS LogTimestamp,
								@datacounter					AS RowsAffected 
								FOR XML PATH('Notification'),
								TYPE,
								ROOT('Activity'));

		EXEC dbo.CreateLog @LogType = 'CREATE', @TableName = 'Process', @Metadata = @report;		
		RETURN 0
	END TRY
	BEGIN CATCH
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;
		DECLARE @ErrorTimeStamp DATETIME;
		DECLARE @ErrAction NVARCHAR(25);

		SELECT	@ErrorMessage   = ERROR_MESSAGE(),
				@ErrorSeverity  = ERROR_SEVERITY(),
				@ErrorState     = ERROR_STATE(),
				@ErrorTimeStamp = GETDATE(),
				@ErrAction      = 'CREATE';

		SET @report = (SELECT	@ErrorMessage	AS ErrorMessage,
								@ErrAction		AS ErrorAction,
								@ErrorSeverity	AS ErrorSeverity,
								@ErrorState		AS ErrorState,
								@ErrorTimeStamp AS ErrorTimestamp 
								FOR XML PATH('Error'), 
								TYPE, 
								ROOT('ErrorLog'));		

		EXEC dbo.CreateErrorLog @ErrorType = 'ERROR', @ErrorAction = @ErrAction, @TableName = 'Process', @Metadata = @report;
	END CATCH
END